package com.crm.base.utils;

import com.crm.base.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * @Author：Albert
 * @Version：1.0
 * @Date：2024/7/13-15:14
 * @Since：jdk1.8
 * @Description：
 */
public class JWTUtils {
    public static String create(Map<String, Object> map) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(map);

            String jwt = Jwts.builder().claim("data", s)
                    .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60000))
                    .signWith(SignatureAlgorithm.HS256, "xiaochen")
                    .compact();
            return jwt;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static User parse(String jwt) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Jwt xiaochen = Jwts.parser().setSigningKey("xiaochen").parse(jwt);
            Map<String, Object> body = (Map<String, Object>) xiaochen.getBody();
            String str = (String) body.get("data");
            User user = mapper.readValue(str, User.class);

            return user;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
